/** biome-ignore-all lint/a11y/useSemanticElements: ignore semantic elements */
import { Draggable } from "@hello-pangea/dnd";
import { ContextMenu } from "@renderer/components/ui/base/context-menu";
import { useDragableTab } from "@renderer/hooks/use-dragable-tab";
import { usePrivacyMode } from "@renderer/hooks/use-privacy-mode";
import { cn } from "@renderer/lib/utils";
import { useThreadWithMessagesStatus } from "@renderer/queries/hooks/use-threads";
import type { TabType } from "@shared/triplit/types";
import { motion } from "motion/react";
import { useTranslation } from "react-i18next";
import { ModalAction } from "../modal-action";
import { ShrinkableTab } from "./shrinkable-tab";

interface TabProps {
  className?: string;
  tabId: string;
  threadId: string;
  index: number;
  title: string;
  isActive: boolean;
  onClick: () => void;
  width: number;
  type: TabType;
  isPrivate?: boolean;
}

const noDragRegion = { WebkitAppRegion: "no-drag" } as React.CSSProperties;

export function Tab({
  className,
  tabId,
  threadId,
  index,
  title,
  isActive,
  onClick,
  width,
  type,
  isPrivate = false,
}: TabProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "tab-bar.menu-item",
  });
  const {
    handleTabClose,
    handleTabCloseAll,
    handleTabReload,
    handleTabCloseOthers,
    handleTabCloseRight,
    handleNewTab,
    handleGenerateTitle,
    handleCleanMessages,
    handleCreateBranch,
    handleCopyAllMessages,
    handleCopyLatestAIMessage,
    handleScreenshotChat,
    handleOpenInBrowser,
    cleanModalOpen,
    setCleanModalOpen,
    closeModal,
  } = useDragableTab({
    id: tabId,
    threadId,
    index,
  });

  const { togglePrivacyMode } = usePrivacyMode();

  const handleChangeToPrivate = async () => {
    await togglePrivacyMode(tabId);
  };

  const isHomePage = threadId === "" && type === "thread";
  const isChatPage = threadId && type === "thread";

  const { data: status } = useThreadWithMessagesStatus(threadId);

  const isStreaming = status === "pending";
  const isAiToolTab = type === "302ai-tool";

  // * The three different compression states for the tab
  const isShrinkedThree = width <= 50;

  return (
    <>
      <Draggable draggableId={tabId} index={index}>
        {(provided, snapshot) => (
          <ContextMenu>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.5 }}
              className="h-[74%]"
            >
              <ContextMenu.Trigger className="size-full">
                <div
                  ref={(node) => {
                    provided.innerRef(node);
                  }}
                  {...provided.draggableProps}
                  {...provided.dragHandleProps}
                  className={cn(
                    "relative flex h-full select-none items-center rounded-[10px]",
                    isShrinkedThree
                      ? "justify-center px-1"
                      : "justify-between px-3",
                    isActive
                      ? "bg-accent text-accent-fg"
                      : "hover:bg-hover hover:text-hover-fg",
                    snapshot.isDragging ? "opacity-50" : "opacity-100",
                    className,
                  )}
                  onClick={onClick}
                  onMouseDown={(e) => {
                    if (e.button === 1) {
                      e.preventDefault();
                      e.stopPropagation();
                      handleTabClose();
                    }
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.stopPropagation();
                      onClick();
                    }
                  }}
                  role="button"
                  tabIndex={0}
                  style={
                    {
                      width: `${width}px`,
                      minWidth: `${width}px`,
                      maxWidth: `${width}px`,
                      ...noDragRegion,
                      ...provided.draggableProps.style,
                      cursor: "pointer",
                    } as React.CSSProperties
                  }
                >
                  <ShrinkableTab
                    title={title}
                    isActive={isActive}
                    width={width}
                    type={type}
                    handleTabClose={handleTabClose}
                    streaming={isStreaming}
                    isPrivate={isPrivate}
                  />
                </div>
              </ContextMenu.Trigger>
            </motion.div>
            <ContextMenu.Content aria-label={`Tab options for ${title}`}>
              <ContextMenu.Item onAction={handleNewTab}>
                {t("new-tab")}
              </ContextMenu.Item>

              {isChatPage && (
                <>
                  <ContextMenu.Separator />
                  <ContextMenu.Item onAction={handleGenerateTitle}>
                    {t("generate-title")}
                  </ContextMenu.Item>
                  <ContextMenu.Item
                    onAction={() => setCleanModalOpen("clean-messages")}
                  >
                    {t("clean-messages")}
                  </ContextMenu.Item>
                  <ContextMenu.Separator />
                  <ContextMenu.Item onAction={handleCreateBranch}>
                    {t("create-branch")}
                  </ContextMenu.Item>
                  <ContextMenu.Separator />
                  <ContextMenu.Item onAction={handleCopyAllMessages}>
                    {t("copy-all-messages")}
                  </ContextMenu.Item>
                  <ContextMenu.Item onAction={handleCopyLatestAIMessage}>
                    {t("copy-latest-message")}
                  </ContextMenu.Item>
                  {isActive && (
                    <>
                      <ContextMenu.Separator />
                      <ContextMenu.Item onAction={handleScreenshotChat}>
                        {t("screenshot-chat")}
                      </ContextMenu.Item>
                    </>
                  )}
                </>
              )}
              <ContextMenu.Separator />
              {isAiToolTab && (
                <>
                  <ContextMenu.Item onAction={handleTabReload}>
                    {/* <RotateCw className="mr-2 h-4 w-4" /> */}
                    {t("reload")}
                  </ContextMenu.Item>

                  <ContextMenu.Item onAction={handleOpenInBrowser}>
                    {/* <RotateCw className="mr-2 h-4 w-4" /> */}
                    {t("open-in-browser")}
                  </ContextMenu.Item>
                  <ContextMenu.Separator />
                </>
              )}
              {isHomePage && (
                <>
                  <ContextMenu.Item onAction={handleChangeToPrivate}>
                    {/* <Ghost className="mr-2 h-4 w-4" /> */}
                    {t(isPrivate ? "change-to-public" : "change-to-private")}
                  </ContextMenu.Item>
                  <ContextMenu.Separator />
                </>
              )}
              <ContextMenu.Item onAction={handleTabClose}>
                {/* <X className="mr-2 h-4 w-4" /> */}
                {t("close")}
              </ContextMenu.Item>

              <ContextMenu.Item onAction={handleTabCloseOthers}>
                {/* <CopyX className="mr-2 h-4 w-4" /> */}
                {t("close-others")}
              </ContextMenu.Item>

              <ContextMenu.Item onAction={handleTabCloseRight}>
                {/* <CopyX className="mr-2 h-4 w-4" /> */}
                {t("close-right")}
              </ContextMenu.Item>
              <ContextMenu.Item onAction={handleTabCloseAll}>
                {/* <CopyX className="mr-2 h-4 w-4" /> */}
                {t("close-all")}
              </ContextMenu.Item>
            </ContextMenu.Content>
          </ContextMenu>
        )}
      </Draggable>

      <ModalAction
        state={cleanModalOpen}
        onOpenChange={closeModal}
        actionType={{
          title: t("thread-menu.actions.clean-messages.title", {
            keyPrefix: "",
          }),
          descriptions: [
            t("thread-menu.actions.clean-messages.description", {
              keyPrefix: "",
            }),
          ],
          confirmText: t("thread-menu.actions.clean-messages.confirmText", {
            keyPrefix: "",
          }),
          action: handleCleanMessages,
          disabled: false,
          isPending: false,
        }}
      />
    </>
  );
}
